//
//  RequestAPI.swift
//  perfmall
//
//  Created by why on 2019/12/11.
//  Copyright © 2019 mallae. All rights reserved.
//

import Foundation
import Moya

extension String {
    var urlEscaped: String {
        return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
}

enum requestAPI {
    case requestUrlString(parameters: String)
    case requestUrlDict(parametersStr: String,parametersDict:[String : Any])
    case requestUrlDictWithNewHost(parametersStr: String,parametersDict:[String : Any])
    case uploadAvatarImgae(parametersDict:[String : Any],imageData : Array<Data>)
}

extension requestAPI:TargetType{
    
    var baseURL: URL {

        return URL.init(string: "https://carpool.wm69.mintennet.com")!
    }
    
    var path: String {
        switch self {
        case .requestUrlString(let urlStr):
            return "/api/client/\(urlStr)"
        case .requestUrlDict(let urlStr, parametersDict: _):
            return "/api/client/\(urlStr)"
        case .requestUrlDictWithNewHost(let urlStr, parametersDict: _):
            return urlStr
        case .uploadAvatarImgae(parametersDict: _, imageData: _):
            return "/api/upload/img_up"
        }
    }
 
        
    var method: Moya.Method {
        switch self {
        case .requestUrlDict(parametersStr: _,parametersDict: _):
            return .post
        case .requestUrlString(parameters: _):
            return .get
        default:
            return .post
        }
    }
    
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        switch self {
        case .requestUrlString(_):
            return .requestPlain
        case let .requestUrlDict(_,parameters):
            return .requestParameters(parameters: parameters, encoding: JSONEncoding.default)
        case let .requestUrlDictWithNewHost(_,parameters):
            return .requestParameters(parameters: parameters, encoding: JSONEncoding.default)
        case .uploadAvatarImgae( let parameters, let imageData):
            var imageArray:Array<MultipartFormData> = []
            for data in imageData {
                let formData = MultipartFormData(provider: .data(data), name: "file[]",
                fileName: "post.png", mimeType: "image/png")
                imageArray.append(formData)
            }
            
            return .uploadCompositeMultipart(imageArray, urlParameters: parameters)
        }
    }
    
    var headers: [String : String]? {
     
        return ["Content-Type": "multipart/form-data"]
    }
    
    
}
